import 'dart:async';

import 'lifecycle.dart';
import 'live_data.dart';

extension LDStringExtends on String {
  StreamSubscription<dynamic> bus(LifecycleOwner lifecycleOwner, Observer<dynamic> observer) {
    return EventBus.get(this).observe(lifecycleOwner, observer);
  }

  StreamSubscription<dynamic> busForever(Observer<dynamic> observer) {
    return EventBus.get(this).observeForever(observer);
  }

  void unBus(Observer<dynamic> observer) {
    EventBus.get(this).removeObserver(observer);
  }

  void busPost(dynamic value) {
    EventBus.get(this).post(value);
  }
}

extension LDLifecycleOwnerExtends on LifecycleOwner {
  StreamSubscription<dynamic> bus(String key, Observer<dynamic> observer) {
    return EventBus.get(key).observe(this, observer);
  }
}

class EventBus {
  final Map<String, LiveData<dynamic>> _bus = {};

  factory EventBus() {
    return _instance;
  }

  EventBus._internal();

  static final EventBus _instance = EventBus._internal();

  LiveData<dynamic> withKey(String key) {
    if (!_bus.containsKey(key)) {
      _bus[key] = LiveData<dynamic>();
    }
    return _bus[key]!;
  }

  static EventBus get instance => _instance;

  static LiveData<dynamic> get(String key) => instance.withKey(key);
}
